#!/usr/bin/env bash

set -e
set -x

if [[ $1 == "" ]]; then
    echo "Test local lfortran"
    PATH="$(pwd):$PATH"
    FC=lfortran
elif [[ $1 == "gfortran" ]]; then
    echo "Test installed gfortran"
    FC=gfortran
elif [[ $1 == "lfortran" ]]; then
    echo "Test installed lfortran"
    FC=lfortran
else
    echo "Invalid option"
    exit 1
fi

f=`pwd`/examples/expr2.f90
ASM_PATTERN="movq\|movl\|retq"

cd $(mktemp -d)
$FC $f -o a.out
[ -f "a.out" ]
[ -x "a.out" ]
./a.out

cd $(mktemp -d)
$FC -c $f
[ -f "expr2.o" ]
[ ! -x "expr2.o" ]
$FC -o expr2 expr2.o
[ -f "expr2" ]
[ -x "expr2" ]
./expr2

cd $(mktemp -d)
$FC -o xx1 -c $f
[ -f "xx1" ]
[ ! -x "xx1" ]
$FC -o expr2 xx1
[ -f "expr2" ]
[ -x "expr2" ]
./expr2

cd $(mktemp -d)
$FC -o xx1 $f
[ -f "xx1" ]
[ -x "xx1" ]
./xx1

cd $(mktemp -d)
$FC -S $f
[ -f "expr2.s" ]
grep $ASM_PATTERN expr2.s

cd $(mktemp -d)
$FC -S -c $f
[ -f "expr2.s" ]
grep $ASM_PATTERN expr2.s

cd $(mktemp -d)
$FC -S -o xx1 $f
[ -f "xx1" ]
grep $ASM_PATTERN xx1

cd $(mktemp -d)
$FC -S -o xx1 -c $f
[ -f "xx1" ]
grep $ASM_PATTERN xx1

echo "All tests succeeded"
